package com.example.blog.common.utils;

import com.example.blog.common.exception.ServiceException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.Map;

public class ExportUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static Resource exportToExcel(String sheetName, List<String> headers, List<List<Object>> data) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(sheetName);

            // 创建标题行样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setAlignment(HorizontalAlignment.CENTER);

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers.get(i));
                cell.setCellStyle(headerStyle);
                sheet.autoSizeColumn(i);
            }

            // 填充数据
            for (int i = 0; i < data.size(); i++) {
                Row row = sheet.createRow(i + 1);
                List<Object> rowData = data.get(i);
                for (int j = 0; j < rowData.size(); j++) {
                    Cell cell = row.createCell(j);
                    Object value = rowData.get(j);
                    if (value != null) {
                        if (value instanceof Number) {
                            cell.setCellValue(((Number) value).doubleValue());
                        } else {
                            cell.setCellValue(value.toString());
                        }
                    }
                }
            }

            // 导出为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return new ByteArrayResource(outputStream.toByteArray());
        } catch (Exception e) {
            throw new ServiceException("导出Excel失败：" + e.getMessage());
        }
    }

    public static Resource exportToJson(Object data) {
        try {
            byte[] jsonBytes = objectMapper.writeValueAsBytes(data);
            return new ByteArrayResource(jsonBytes);
        } catch (Exception e) {
            throw new ServiceException("导出JSON失败：" + e.getMessage());
        }
    }

    public static Resource exportToCsv(List<String> headers, List<List<Object>> data) {
        try {
            StringBuilder csv = new StringBuilder();
            
            // 添加UTF-8 BOM
            csv.append('\ufeff');
            
            // 添加标题行
            csv.append(String.join(",", headers)).append("\n");
            
            // 添加数据行
            for (List<Object> row : data) {
                csv.append(
                    row.stream()
                        .map(cell -> cell == null ? "" : escapeSpecialCharacters(cell.toString()))
                        .reduce((a, b) -> a + "," + b)
                        .orElse("")
                ).append("\n");
            }
            
            return new ByteArrayResource(csv.toString().getBytes("UTF-8"));
        } catch (Exception e) {
            throw new ServiceException("导出CSV失败：" + e.getMessage());
        }
    }
    
    private static String escapeSpecialCharacters(String data) {
        String escapedData = data.replaceAll("\"", "\"\"");
        if (escapedData.contains(",") || escapedData.contains("\"") || escapedData.contains("\n")) {
            escapedData = "\"" + escapedData + "\"";
        }
        return escapedData;
    }
} 